package com.zygk.library.util;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {
  public static String brand = android.os.Build.BRAND;//手机品牌
  private static Util util;
  public static int flag = 0;
  private double r = 6371.004;

  private Util() {

  }

  public static Util getInstance() {
    if (util == null) {
      util = new Util();
    }
    return util;
  }

  /**
   * 手机类型(1:小米 2:华为 0:其它)
   */
  public int phoneType() {
    int phoneType = 0;
    if (Util.brand.equalsIgnoreCase("xiaomi")) {
      phoneType = 1;
    } else if (Util.brand.equalsIgnoreCase("huawei") || Util.brand.equalsIgnoreCase("honor")) {
      phoneType = 2;
    }

    return phoneType;
  }

  /**
   * 判断是否有sdcard
   */
  public boolean hasSDCard() {
    boolean b = false;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      b = true;
    }
    return b;
  }

  /**
   * 得到sdcard路径
   */
  public String getExtPath() {
    String path = "";
    if (hasSDCard()) {
      path = Environment.getExternalStorageDirectory().getPath();
    }
    return path;
  }

  /**
   * 得到/data/data/com.d3studio.together目录
   */
  public String getPackagePath(Context mActivity) {
    return mActivity.getFilesDir().toString();
  }

  /**
   * 根据url得到图片
   */
  public String getImageName(String url) {
    String imageName = "";
    if (url != null) {
      imageName = url.substring(url.lastIndexOf("/") + 1);
    }
    return imageName;
  }

  /**
   * 根据经纬度获取距离
   */
  public String getDistance(double lat1, double lon1, double lat2, double lon2) {
    String string;

    //上传位置失败时===  0.0没办法，百度地图的蛋疼设定，唯有丢失非洲用户啦
    if (lat2 == 0 && lon2 == 0) {
      string = "暂无数据";
    } else {
      double distance = 0;
      distance = 2 * r * Math.asin(Math.sqrt(
          Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(
              Math.sin((lon1 - lon2) / 2), 2)));
      // 保留两位小数
      DecimalFormat df = new DecimalFormat("##.##");
      string = df.format(distance) + "km";
    }
    return string;
  }

  /**
   * 判断手机号码的正确性
   */
  public boolean isMobileNumber(String mobiles) {
    Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
    Matcher m = p.matcher(mobiles);
    return m.matches();
  }

  /**
   * 判断邮箱的正确性
   */
  public static boolean isEmail(String email) {
    Pattern p = Pattern.compile(
        "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
    Matcher m = p.matcher(email);
    return m.matches();
  }

  /**
   * 不能全是相同的数字或者字母
   */
  public boolean equalStr(String numOrStr) {
    boolean flag = true;
    char str = numOrStr.charAt(0);
    for (int i = 0; i < numOrStr.length(); i++) {
      if (str != numOrStr.charAt(i)) {
        flag = false;
        break;
      }
    }
    return flag;
  }

  // 不能是连续的数字--递增
  public boolean isOrderNumeric(String numOrStr) {
    boolean flag = true;
    boolean isNumeric = true;
    for (int i = 0; i < numOrStr.length(); i++) {
      if (!Character.isDigit(numOrStr.charAt(i))) {
        isNumeric = false;
        break;
      }
    }
    if (isNumeric) {
      for (int i = 0; i < numOrStr.length(); i++) {
        if (i > 0) {
          int num = Integer.parseInt(numOrStr.charAt(i) + "");
          int num_ = Integer.parseInt(numOrStr.charAt(i - 1) + "") + 1;
          if (num != num_) {
            flag = false;
            break;
          }
        }
      }
    } else {
      flag = false;
    }
    return flag;
  }

  // 不能是连续的数字--递减
  public boolean isOrderNumeric_(String numOrStr) {
    boolean flag = true;
    boolean isNumeric = true;
    for (int i = 0; i < numOrStr.length(); i++) {
      if (!Character.isDigit(numOrStr.charAt(i))) {
        isNumeric = false;
        break;
      }
    }
    if (isNumeric) {
      for (int i = 0; i < numOrStr.length(); i++) {
        if (i > 0) {
          int num = Integer.parseInt(numOrStr.charAt(i) + "");
          int num_ = Integer.parseInt(numOrStr.charAt(i - 1) + "") - 1;
          if (num != num_) {
            flag = false;
            break;
          }
        }
      }
    } else {
      flag = false;
    }
    return flag;
  }

  // 遍历布局，并禁用所有子控件 -- 不禁止TextView
  public static void disableSubControls(ViewGroup viewGroup) {
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
      View v = viewGroup.getChildAt(i);
      if (v instanceof ViewGroup) {
        if (v instanceof Spinner) {
          Spinner spinner = (Spinner) v;
          spinner.setClickable(false);
          spinner.setEnabled(false);
        } else if (v instanceof ListView) {
          ((ListView) v).setClickable(false);
          ((ListView) v).setEnabled(false);
        } else {
          disableSubControls((ViewGroup) v);
        }
      } else if (v instanceof EditText) {
        ((EditText) v).setEnabled(false);
        ((EditText) v).setClickable(false);
      } else if (v instanceof Button) {
        ((Button) v).setEnabled(false);
      }
    }
  }

  // 遍历布局，并禁用所有子控件  -- 不禁止TextView
  public static void ableSubControls(ViewGroup viewGroup) {
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
      View v = viewGroup.getChildAt(i);
      if (v instanceof ViewGroup) {
        if (v instanceof Spinner) {
          Spinner spinner = (Spinner) v;
          spinner.setClickable(true);
          spinner.setEnabled(true);
        } else if (v instanceof ListView) {
          ((ListView) v).setClickable(true);
          ((ListView) v).setEnabled(true);
        } else {
          ableSubControls((ViewGroup) v);
        }
      } else if (v instanceof EditText) {
        ((EditText) v).setEnabled(true);
        ((EditText) v).setClickable(true);
      } else if (v instanceof Button) {
        ((Button) v).setEnabled(true);
      }
    }
  }

  // 隐藏手机键盘
  public static void hideIM(Context context, View edt) {
    try {
      InputMethodManager im =
          (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
      IBinder windowToken = edt.getWindowToken();
      if (windowToken != null) {
        im.hideSoftInputFromWindow(windowToken, 0);
        //             System.out.println("done");
      }
    } catch (Exception e) {
      //     	System.out.println("失败");
    }
  }

  /**
   * 检测当的网络（WLAN、3G/2G）状态
   *
   * @param context Context
   * @return true 表示网络可用
   */
  public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
      NetworkInfo info = connectivity.getActiveNetworkInfo();
      if (info != null && info.isConnected()) {
        // 当前网络是连接的
        if (info.getState() == NetworkInfo.State.CONNECTED) {
          // 当前所连接的网络可用
          return true;
        }
      }
    }
    return false;
  }

  //判断通知栏是否打开
  public static boolean isNotificationEnabled(Context context) {

    String CHECK_OP_NO_THROW = "checkOpNoThrow";
    String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    ApplicationInfo appInfo = context.getApplicationInfo();
    String pkg = context.getApplicationContext().getPackageName();
    int uid = appInfo.uid;

    Class appOpsClass = null;
      /* Context.APP_OPS_MANAGER */
    try {
      appOpsClass = Class.forName(AppOpsManager.class.getName());
      Method checkOpNoThrowMethod =
          appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
      Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

      int value = (Integer) opPostNotificationValue.get(Integer.class);
      return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg)
          == AppOpsManager.MODE_ALLOWED);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    return false;
  }

  /**
   * 打开允许通知的设置页
   */
  public static void goToNotificationSetting(Context context) {
    Intent intent = new Intent();
    if (Build.VERSION.SDK_INT >= 26) {
      // android 8.0引导
      intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
      intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
    } else if (Build.VERSION.SDK_INT >= 21) {
      // android 5.0-7.0
      intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
      intent.putExtra("app_package", context.getPackageName());
      intent.putExtra("app_uid", context.getApplicationInfo().uid);
    } else {
      // 其他
      intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
      intent.setData(Uri.fromParts("package", context.getPackageName(), null));
    }
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
  }

  public static Bitmap createVideoThumbnail(String filePath) {
    // MediaMetadataRetriever is available on API Level 8
    // but is hidden until API Level 10
    Class<?> clazz = null;
    Object instance = null;
    try {
      clazz = Class.forName("android.media.MediaMetadataRetriever");
      instance = clazz.newInstance();

      Method method = clazz.getMethod("setDataSource", String.class);
      method.invoke(instance, filePath);

      // The method name changes between API Level 9 and 10.
      if (Build.VERSION.SDK_INT <= 9) {
        return getRoundedCornerBitmap((Bitmap) clazz.getMethod("captureFrame").invoke(instance));
      } else {
        byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
        if (data != null) {
          Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
          if (bitmap != null) return getRoundedCornerBitmap(bitmap);
        }
        return getRoundedCornerBitmap((Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance));
      }
    } catch (IllegalArgumentException ex) {
      // Assume this is a corrupt video file
    } catch (RuntimeException ex) {
      // Assume this is a corrupt video file.
    } catch (InstantiationException e) {
      Log.e("TAG", "createVideoThumbnail", e);
    } catch (InvocationTargetException e) {
      Log.e("TAG", "createVideoThumbnail", e);
    } catch (ClassNotFoundException e) {
      Log.e("TAG", "createVideoThumbnail", e);
    } catch (NoSuchMethodException e) {
      Log.e("TAG", "createVideoThumbnail", e);
    } catch (IllegalAccessException e) {
      Log.e("TAG", "createVideoThumbnail", e);
    } finally {
      try {
        if (instance != null) {
          clazz.getMethod("release").invoke(instance);
        }
      } catch (Exception ignored) {
      }
    }
    return null;
  }

  public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = 13;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
  }

  public static Map createVideoThumbnail(String filePath, int kind) {
    Bitmap bitmap = null;
    String duration = null;
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try
    {
      if (filePath.startsWith("http://")
          || filePath.startsWith("https://")
          || filePath.startsWith("widevine://"))
      {
        retriever.setDataSource(filePath, new Hashtable<String, String>());
      }
      else
      {
        retriever.setDataSource(filePath);
      }
      bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //retriever.getFrameAtTime(-1);
      duration = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
    }
    catch (IllegalArgumentException ex)
    {
      // Assume this is a corrupt video file
      ex.printStackTrace();
    }
    catch (RuntimeException ex)
    {
      // Assume this is a corrupt video file.
      ex.printStackTrace();
    }
    finally
    {
      try
      {
        retriever.release();
      }
      catch (RuntimeException ex)
      {
        // Ignore failures while cleaning up.
        ex.printStackTrace();
      }
    }

    if (bitmap == null)
    {
      return null;
    }

    if (kind == MediaStore.Images.Thumbnails.MINI_KIND)
    {//压缩图片 开始处
      // Scale down the bitmap if it's too large.
      int width = bitmap.getWidth();
      int height = bitmap.getHeight();
      int max = Math.max(width, height);
      if (max > 512)
      {
        float scale = 512f / max;
        int w = Math.round(scale * width);
        int h = Math.round(scale * height);
        bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
      }//压缩图片 结束处
    }
    else if (kind == MediaStore.Images.Thumbnails.MICRO_KIND)
    {
      bitmap = ThumbnailUtils.extractThumbnail(bitmap,96,96,
          ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    }
    Map map = new HashMap();
    map.put("bitmap", getRoundedCornerBitmap(compressImage(bitmap)));
    map.put("duration", Integer.parseInt(duration)/1000);
    return map;
  }

  /**
   * 质量压缩方法
   *
   * @param image
   * @return
   */
  public static Bitmap compressImage(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
    int options = 90;

    while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
      baos.reset(); // 重置baos即清空baos
      image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
      options -= 10;// 每次都减少10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
    return bitmap;
  }
}